TOOL.Category = '(Water Works)'
TOOL.Name = 'Generators'
TOOL.Command = nil
TOOL.ConfigName = ''

TOOL.ClientConVar['wrtype'] = 'turbine'

if ( CLIENT ) then
	language.Add( 'Tool_watergen_name', 'Water Works Storage (PhonicUK)' )
	language.Add( 'Tool_watergen_desc', 'Create Water / Steam Generators' )
	language.Add( 'Tool_watergen_0', 'Click to spawn a device. Right click to spawn without weld.' )
	language.Add( 'Undone_watergen', 'Undone Water Generator.' )
end

function TOOL.BuildCPanel( panel )
	panel:AddControl( 'Header', { Text = '#Tool_watergen_name', Description	= '#Tool_watergen_desc' }  )

	local combobox = {Label = "#Water Works Storage Unit", MenuButton = 0, Options={}}
		combobox["Options"]["#Steam Turbine"]	= { watergen_wrtype = "turbine" }
		combobox["Options"]["#Steam Micro Turbine"]	= { watergen_wrtype = "turbine_small" }
		combobox["Options"]["#Large Steam Turbine"]	= { watergen_wrtype = "turbine_large" }
		combobox["Options"]["#Water Electrolyzer"]	= { watergen_wrtype = "water_electrolyzer" }
		combobox["Options"]["#Steam Heat Exchanger"]	= { watergen_wrtype = "steam_exchanger" }
	panel:AddControl("ComboBox", combobox) 
end

function TOOL:LeftClick( trace )
	local Ang = trace.HitNormal:Angle()
 	Ang.pitch = Ang.pitch + 90
	createdev( trace, true, self, self:GetClientInfo('wrtype'), Ang )
	return true
end    

function TOOL:RightClick( trace )
	local Ang = trace.HitNormal:Angle() 
 	Ang.pitch = Ang.pitch + 90
	createdev( trace, false, self, self:GetClientInfo('wrtype'), Ang )
	return true
end

function createdev(trace, weldit, self1, gentype, ang)
	if( SERVER ) then
		-- Get trace entity
		local ent0 = trace.Entity
	
		--Create generator
		local ent1 = ents.Create( gentype )
		ent1:SetAngles( ang ) 
		local mins = ent1:OBBMins()
		ent1:SetPos( trace.HitPos + trace.HitNormal * mins.z )
		ent1:Spawn()
		ent1:Activate()
		ent1:SetVar('Owner',self1:GetOwner())
	
		-- Weld it only to props
		if (weldit == true) then
		local weld = constraint.Weld(ent0, ent1, trace.PhysicsBone, 0, 0)
		end 
	
		-- This seems not to work :S:S:S:S:S:S:S
		undo.Create("watergen") 
			undo.AddEntity( weld ) 
			undo.AddEntity( ent1 ) 
			undo.SetPlayer( self1:GetOwner() ) 
		undo.Finish()
		return ent1
	end
end